#include "os_port.h"
#include <pthread.h>
#include <time.h>


pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
uint32_t  g_tick = 0;

struct timespec g_time = {
    .tv_sec = 0,
    .tv_nsec = 1000000 // 1 millisecond
};


static void __sleep_ms(uint32_t ms)
{
    struct timespec req = g_time;
    req.tv_sec = ms / 1000;
    req.tv_nsec = (ms % 1000) * 1000000; // Convert milliseconds to nanoseconds
    nanosleep(&req, NULL);
}

uint32_t get_systick(void)
{
    uint32_t tick;
    pthread_mutex_lock(&g_mutex); // Lock the mutex to ensure thread safety
    tick =  g_tick;
    pthread_mutex_unlock(&g_mutex); // Unlock the mutex after accessing the tick
    return tick;
}

void get_systick_thread(void * arg)
{
    while(1)
    {
        pthread_mutex_lock(&g_mutex); // Lock the mutex to ensure thread safety
        g_tick ++;
        pthread_mutex_unlock(&g_mutex); // Unlock the mutex after accessing the tick
        __sleep_ms(1); // Sleep for 1 millisecond
    }
}


